package com.maimao.user.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.maimao.core.constant.ListData;
import com.maimao.core.constant.RedisKeys;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.model.user.Foot;
import com.maimao.user.client.GoodsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author MaoLin Wang
 * @date 2021/1/26 12:17 下午
 */
@Service
public class FootService {
    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private GoodsClient goodsClient;

    /**
     * 只保存100个足迹
     *
     * @param userId
     * @param goodsId
     */
    public void save(Long userId, Long goodsId) {
        redisTemplate.opsForZSet().add(String.format(RedisKeys.FOOT, userId), goodsId, System.currentTimeMillis());
    }

    public List<Foot> userFootData(Long userId) {
        Set<Long> goodsIds = redisTemplate.opsForZSet().reverseRange(String.format(RedisKeys.FOOT, userId), 0, -1);
        if (goodsIds != null && goodsIds.size() > 0) {
            List<Long> goodsIdsL = Lists.newArrayList(goodsIds);
            if (goodsIdsL.size() > 100) {
                //清除超过100个的足迹
                List<Long> removeIds = goodsIdsL.subList(100, goodsIdsL.size());
                redisTemplate.opsForZSet().remove(String.format(RedisKeys.FOOT, userId),removeIds);
                goodsIdsL = goodsIdsL.subList(0, 100);
            }
            Result<List<Foot>> footGoodsRes = goodsClient.userFoot(goodsIdsL);
            if (footGoodsRes != null) {
                return footGoodsRes.getData();
            }
        }
        return ListData.EMPTY_LIST;
    }

    private String getFootKey() {
        Integer[] yearMonthDay = DateUtils.getYearMonthDay(0);
        String key = "";
        for (Integer item : yearMonthDay) {
            key += item;
        }
        return key;
    }

    private String[] getFootKey30day(Long userId) {
        String[] keys = new String[30];
        for (int i = 0; i < 30; i++) {
            Integer[] yearMonthDay = DateUtils.getYearMonthDay(i);
            String key = userId.toString() + "_";
            for (Integer item : yearMonthDay) {
                key += item;
            }
            keys[i] = key;
        }

        return keys;
    }
}
